#!/usr/bin/env python
# coding=utf-8
import redis
import json
import sys
import requests
'''
'''
#message = "INFO: The ansible tasks taskid 101 starting running"
#message = "exception: The ansible tasks taskid 101 starting running"

def dingding_notice(message,try_times):
    message_full = 'exception:' + message
    data_string = json.dumps(
        {
		    'url':'https://oapi.dingtalk.com/robot/send?access_token=e3ec4dfcb86f148bc7de1d19a86500932ee490b35b5a32c2a712ec0ffd35cb9b',
		    'groupname': 'ghd',
                    'msgtype': 'text',
                    'text': {
                            'content': message_full
                            }
        })
    print data_string
    webhook = "https://oapi.dingtalk.com/robot/send?access_token=e3ec4dfcb86f148bc7de1d19a86500932ee490b35b5a32c2a712ec0ffd35cb9b"
    private_webhook = "https://oapi.dingtalk.com/robot/send?access_token=7ab5c88386460947af52e4de46e8b87821cd573814626c4489541567b620f335"
    ourheaders = {'Content-Type': 'application/json'}
    #requests.post(webhook, headers=ourheaders, data=data_string)
    try:
        r = requests.post(private_webhook, headers=ourheaders, data=data_string)

        if r.status_code == 200:
            if r.text:
                req_res = json.loads(r.text)
                print req_res
                if req_res['errcode'] == 0:
                    return True
                else:
                    return json.dumps(req_res)
        else:
                return False

    except requests.exceptions.Timeout:
        if try_times > 5:
            print "connection timeout, the 5 seconds requests"
            return -1
        try_times += 1
        dingding_notice(message,try_times)

'''
try_times = 1
res = dingding_notice(message,try_times)
print res

{"errcode":0,"errmsg":"ok"}
'''
